package com.nova.android.tvlauncher.ui.view.atv

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.FocusFinder
import android.view.KeyEvent
import android.view.View
import androidx.leanback.widget.OnChildViewHolderSelectedListener
import androidx.leanback.widget.VerticalGridView
import androidx.recyclerview.widget.RecyclerView

/*
 * 拦截过快移动，支持边界向右或向下寻找焦点
 * 修复最后一排不满时焦点跳转问题，倒数第二行向下切换到最后一个 item
 */
class MyVerticalGridView : VerticalGridView {
    private var cacheTime: Long = 0
    private var lastFocusPos = -1
    private var numColumns = 1

    private val myListener = object : OnChildViewHolderSelectedListener() {
        override fun onChildViewHolderSelected(
            parent: RecyclerView,
            child: ViewHolder?,
            position: Int,
            subposition: Int
        ) {
            super.onChildViewHolderSelected(parent, child, position, subposition)
            lastFocusPos = position
            Log.d(TAG, "Selected position: $position")
        }

        override fun onChildViewHolderSelectedAndPositioned(
            parent: RecyclerView,
            child: ViewHolder?,
            position: Int,
            subposition: Int
        ) {
            super.onChildViewHolderSelectedAndPositioned(parent, child, position, subposition)
        }
    }

    constructor(context: Context) : super(context) {
        initView(context)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView(context)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
        initView(context)
    }

    private fun initView(context: Context) {
        addOnChildViewHolderSelectedListener(myListener)
    }

    override fun setNumColumns(numColumns: Int) {
        this.numColumns = numColumns
        super.setNumColumns(numColumns)
        Log.d(TAG, "Num columns set to: $numColumns")
    }

    override fun focusSearch(focused: View, direction: Int): View {
        val nextFocusView = FocusFinder.getInstance().findNextFocus(this, focused, direction)
        if (nextFocusView == null && lastFocusPos != -1 && adapter != null) {
            val totalItems = adapter!!.itemCount
            Log.d(TAG, "Focus search direction: $direction, totalItems: $totalItems, lastFocusPos: $lastFocusPos")

            when (direction) {
                FOCUS_DOWN, FOCUS_RIGHT -> {
                    // 判断是否在倒数第二行
                    val isPenultimateRow = lastFocusPos / numColumns == (totalItems - 1) / numColumns - 1
                    val nextPos = if (isPenultimateRow && totalItems % numColumns != 0) {
                        // 倒数第二行到最后一行的最后一个 item
                        totalItems - 1
                    } else {
                        // 正常情况：跳到下一行第一个 item
                        val currentRowStart = (lastFocusPos / numColumns) * numColumns
                        currentRowStart + numColumns
                    }

                    Log.d(TAG, "Calculated nextPos: $nextPos")

                    // 确保 nextPos 不越界
                    if (nextPos < totalItems) {
                        val nextView = layoutManager?.findViewByPosition(nextPos)
                        if (nextView != null && nextView.isFocusable) {
                            Log.d(TAG, "Found next view at position: $nextPos")
                            return nextView
                        } else {
                            // 如果目标 View 未渲染，滚动到目标位置
                            Log.d(TAG, "Next view not rendered, scrolling to: $nextPos")
                            smoothScrollToPosition(nextPos)
                            // 延迟设置焦点
                            post {
                                val delayedView = layoutManager?.findViewByPosition(nextPos)
                                if (delayedView != null && delayedView.isFocusable) {
                                    delayedView.requestFocus()
                                    Log.d(TAG, "Delayed focus set to position: $nextPos")
                                }
                            }
                            return focused // 返回当前焦点，防止焦点丢失
                        }
                    }
                }
            }
        }
        return nextFocusView ?: super.focusSearch(focused, direction)
    }

    override fun canScrollHorizontally(direction: Int): Boolean {
        val canScrollHorizontally = super.canScrollHorizontally(direction)
        Log.d(TAG, "canScrollHorizontally: $canScrollHorizontally")
        return canScrollHorizontally
    }

    override fun canScrollVertically(direction: Int): Boolean {
        val canScrollVertically = super.canScrollVertically(direction)
        Log.d(TAG, "canScrollVertically: $canScrollVertically")
        return canScrollVertically
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        val action = event.action
        when (event.keyCode) {
            KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN,
            KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> {
                if (action != KeyEvent.ACTION_DOWN) {
                    cacheTime = 0
                    return super.dispatchKeyEvent(event)
                }
                val currentTimeMillis = System.currentTimeMillis()
                if (currentTimeMillis - cacheTime >= 300) {
                    cacheTime = currentTimeMillis
                    return super.dispatchKeyEvent(event)
                }
                return true // 拦截过快按键
            }
        }
        return super.dispatchKeyEvent(event)
    }

    companion object {
        private const val TAG = "MyVerticalGridView"
    }
}